from rqalpha.apis import *
import time
from rqalpha.environment import Environment
from rqalpha.my_factors.book import BookImblance
from rqalpha.my_factors.reform_data import reform_factor_data
from collections import OrderedDict
from rqalpha.const import ORDER_STATUS

config = {
    "base": {
        "start_date": "2021-07-31",
        "end_date": "2021-07-31",
        "frequency": "tick",
        "accounts": {
            "stock": 100000
        }
    },

    "extra": {
        "log_level": "info",
    },

    "mod": {
        "my_backtest": {
            "enabled": True
        },
        "sys_analyser": {
            "enabled": True,
            "benchmark": "000300.XSHG",
            "plot": True,
            "report_save_path": "C:\\Users\\huajia\Desktop\\rqalpha3\\rqalpha\\plot_result"
        },
        "sys_simulation": {
            "matching_type": "best_own",
        },
        "sys_accounts": {
            "validate_stock_position": False,
            "stock_t1": False
        }
    }
}


# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    logger.info("init")
    # 已经做了米筐可以识别的symbol
    _env = Environment.get_instance()
    symbol = _env.config.base.symbol
    context.s1 = symbol
    update_universe(context.s1)
    # 是否已发送了order
    subscribe(context.s1)
    context.order_count = 1
    context.last_order = None


def before_trading(context):
    print('before trading---------------')


# 不可以成交的，一天3笔
# 你选择的证券的数据更新将会触发此段逻辑，例如日或分钟历史数据切片或者是实时数据切片更新
# def handle_bar(context, bar_dict):
def handle_tick(context, tick):
    _env = Environment.get_instance()
    tick_data = tick._tick_dict
    bids_price = tick_data['bids'][0]
    ask_price = tick_data['asks'][0]
    # print(tick_data)
    if context.order_count <= 4:
        # print(tick)
        # print(tick_data)
        if tick_data['volume_add'] > 100000:
            this_order = order_shares(context.s1, 100, style=LimitOrder(12)) if context.order_count <= 3 else \
                context.last_order
            context.last_order = this_order
            context.order_count = context.order_count + 1
        _open_orders = _env.get_open_orders(context.s1)
        # print('latest order:', context.last_order.order_id)
        # print('latest open orders:', [o.order_id for o in _open_orders])
        for o in _open_orders:
            # if tick.datetime != o.trading_datetime:
            #     print('time not matching')
            # else:
            #     print('matching time')
            # print(tick.datetime, o.trading_datetime)
            # print((tick.datetime - o.trading_datetime).microseconds)
            # time.sleep(5)

            if 0.5 * 10**6 <= (tick.datetime - o.trading_datetime).microseconds <= 10 * 10**6:
                print('cancel orders:{}, create time:{}, cancel time:{}'.format(o.order_id,
                                                                                o.trading_datetime, tick.datetime))
                cancel_order(o)

    context.fired = True


def after_trading(context):
    print('after trading----------------')
    context.order_count = 1
    # time.sleep(300)
